// 定义一个user的状态管理
export const userState = defineStore('user', {
    // 定义状态
    state: () => {
        return {
            uuid: "",
            username: "",
            account: "",
            avatar: "",
            token: "",
            roles:[],
            menus:[],
            systemList:[],
            permissions:[]
        }
    },

    // 修改状态
    actions: {
        setMenuApis(menuApis) {
            if(menuApis.permissions && menuApis.permissions.length > 0) {
                this.permissions = menuApis.permissions.map(c=>c.code);
            } else {
                this.permissions = []
            }
            if(menuApis.menus && menuApis.menus.length > 0) {
                this.menus = menuApis.menus.map(c=>{
                    if(!c.children){
                        c.children = []
                    }
                    return c;
                });
            } else {
                this.menus = []
            }
        },
        setLoginUserInfo(user) {
            this.uuid = user.uuid
            this.username = user.username
            this.account = user.account
            this.avatar = user.avatar
            this.token = user.token
            if (user.roles && user.roles.length > 0 ) {
                this.roles = user.roles.map((c, index) => {
                    return {id: c.id, name: c.roleName, active: index == 0}
                });
            }
            if(user.permissions && user.permissions.length > 0) {
                this.permissions = user.permissions.map(c=>c.code);
            }
            if(user.menus && user.menus.length > 0) {
                this.menus = user.menus.map(c=>{
                    if(!c.children){
                        c.children = []
                    }
                    return c;
                });
            }
        }
    },

    // 状态数据获取和加工，和computed一样，定义的是方法使用的时候是属性
    getters: {
        isLogin() {
            return this.uuid != ""
        }
    },

    //persist定义要做判断，因为localStorage是客户端参数，所以需要加process.client
    persist: process.client && {
        storage: localStorage, // sessionStorage/localStorage
        key: 'kva-cc-userlogin', // storage的key
    }
})
